package com.party.mobile.biz.wechat;

import com.party.api.dto.wechatPlatform.response.Oauth2AccessTokenResponse;
import com.party.api.service.wechatPlatform.IWechatPlatformService;
import com.party.common.constant.Constant;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.YesNoStatus;
import com.party.core.model.member.MemberExternalApp;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.order.OrderForm;
import com.party.core.model.order.OrderType;
import com.party.core.model.wechat.WechatMerchants;
import com.party.core.model.wechatPlatform.WechatOpenMember;
import com.party.core.model.wechatPlatform.WechatOpenPlatform;
import com.party.core.service.member.IMemberExternalAppService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.IMemberService;
import com.party.core.service.wechat.IWechatMerchantsService;
import com.party.core.service.wechatPlatform.IWechatOpenMemberService;
import com.party.core.service.wechatPlatform.IWechatOpenPlatformService;
import com.party.mobile.biz.wechatPlatform.WechatPlatformBizService;
import com.party.mobile.web.dto.pay.output.PayParam;
import com.party.mobile.web.dto.wechat.input.AccessTokenResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;

/**
 * 开放平台合作上接口
 * party
 * Created by wei.li
 * on 2017/11/16 0024.
 */

@Service
public class WechatOpenMemberBizService {

    @Autowired
    private WechatBizService wechatBizService;

    @Autowired
    private IWechatOpenMemberService wechatOpenMemberService;

    @Autowired
    private WechatPlatformBizService wechatPlatformBizService;

    @Autowired
    private IWechatPlatformService wechatPlatformService;

    @Autowired
    private IWechatOpenPlatformService wechatOpenPlatformService;

    @Autowired
    private IMemberService memberService;

    @Autowired
    private IMemberExternalAppService memberExternalAppService;

    @Autowired
    private IWechatMerchantsService wechatMerchantsService;

    @Autowired
    private IMemberGroupService memberGroupService;

    @Value("#{wechat_platform['wechat.platform.appId']}")
    private String componentAppid;


    /**
     * 获取授权url(授权走授权配置、没有则走历史数据)
     * @param redirectUri 重定向url
     * @param memberId 会员编号
     * @return 授权url
     * @throws UnsupportedEncodingException
     */
    public String getOathorizeUrl(String redirectUri, String memberId) throws UnsupportedEncodingException {
        String url;
        //使用配置数据
        //MemberMerchant memberMerchant = memberMerchantService.findByMemberId(memberId);
        MemberGroup member = memberGroupService.getPartner(memberId);
        if (member != null && member.getOpenStatus().equals(YesNoStatus.YES.getCode())) {
            if (Constant.DEPLOY_TYPE_AUTH.equals(member.getDeployType())){
                MemberExternalApp memberExternalApp
                        = memberExternalAppService.findByMemberIdAndDeployType(member.getId(),
                        member.getDeployType());
                WechatOpenMember wechatOpenMember = wechatOpenMemberService.get(memberExternalApp.getExternalAccountId());

                //使用授权数据
                if (null != wechatOpenMember){
                    url = wechatPlatformBizService.getOauth2Url(redirectUri, wechatOpenMember.getAuthorizerAppid());
                    return url;
                }
                throw new BusinessException("微信授权不完善");
            }
        }
        url = wechatBizService.getBaseOathorizeUrl(redirectUri, member);
        return url;
    }


    /**
     * 获取用户信息交互凭证
     * @param code 授权码
     * @param memberId 会员编号
     * @return 交互凭证
     */
    public AccessTokenResponse acccessToken(String code, String memberId){
        AccessTokenResponse accessTokenResponse = new AccessTokenResponse();

        MemberGroup member = memberGroupService.getPartner(memberId);
        if (member != null && member.getOpenStatus().equals(YesNoStatus.YES.getCode())) {
            if (Constant.DEPLOY_TYPE_AUTH.equals(member.getDeployType())){

                MemberExternalApp memberExternalApp
                        = memberExternalAppService.findByMemberIdAndDeployType(member.getId(),
                        member.getDeployType());
                WechatOpenMember wechatOpenMember
                        = wechatOpenMemberService.get(memberExternalApp.getExternalAccountId());
                //使用授权数据
                if (null != wechatOpenMember){
                    WechatOpenPlatform wechatOpenPlatform = wechatOpenPlatformService.get();
                    Oauth2AccessTokenResponse oauth2AccessTokenResponse
                            = wechatPlatformService.getOauth2AccessToken(wechatOpenMember.getAuthorizerAppid(), code,
                            componentAppid, wechatOpenPlatform.getComponentAccessToken());

                    if (null != oauth2AccessTokenResponse){
                        accessTokenResponse.setAccessToken(oauth2AccessTokenResponse.getAccessToken());
                        accessTokenResponse.setExpiresIn(oauth2AccessTokenResponse.getExpiresIn());
                        accessTokenResponse.setOpenid(oauth2AccessTokenResponse.getOpenid());
                        accessTokenResponse.setRefreshToken(oauth2AccessTokenResponse.getRefreshToken());
                        accessTokenResponse.setScope(oauth2AccessTokenResponse.getScope());
                    }
                    return accessTokenResponse;
                }
            }
        }

        //使用配置数据
        accessTokenResponse = wechatBizService.acccessToken(code, member);
        return accessTokenResponse;
    }

    /**
     * @param orderForm 订单
     * @return
     * @Author yifeng
     * @Description 获取支付的信息
     * @Date 11:06 2019/4/19
     **/
    public PayParam getPayData(OrderForm orderForm) {
        WechatMerchants wechatMerchantsSystem = wechatMerchantsService.getSystem();
        WechatOpenMember wechatOpenMemberSystem = wechatOpenMemberService.getSystem();
        String mchId = wechatMerchantsSystem.getMerchantId();
        String appId = wechatOpenMemberSystem.getAuthorizerAppid();
        String apiKey = wechatMerchantsSystem.getMerchantApiKey();

        if (orderForm != null) {
            if (orderForm.getType().equals(OrderType.ORDER_CROWD_FUND.getCode())) {
                // 订单绑定的业务发起者 获取绑定商户
                MemberGroup member = memberGroupService.getPartner(orderForm.getInitiatorId());
                if (member != null && member.getOpenStatus().equals(YesNoStatus.YES.getCode())) {
                    MemberExternalApp memberExternalApp
                            = memberExternalAppService.findByMemberIdAndDeployType(member.getId(),
                            member.getDeployType());
                    WechatOpenMember wechatOpenMember
                            = wechatOpenMemberService.get(memberExternalApp.getExternalAccountId());
                    WechatMerchants wechatMerchants
                            = wechatMerchantsService.get(memberExternalApp.getExternalMerchantId());
                    if (StringUtils.isNotEmpty(wechatOpenMember.getAuthorizerAppid())) {
                        appId = wechatOpenMember.getAuthorizerAppid().trim();
                    }
                    if (StringUtils.isNotEmpty(wechatMerchants.getMerchantId())) {
                        mchId = wechatMerchants.getMerchantId().trim();
                    }
                    if (StringUtils.isNotEmpty(wechatMerchants.getMerchantApiKey())) {
                        apiKey = wechatMerchants.getMerchantApiKey().trim();
                    }
                }
            }
        }

        PayParam payParam = new PayParam();
        payParam.setMchId(mchId);
        payParam.setAppId(appId);
        payParam.setApiKey(apiKey);
        return payParam;
    }
}
